import sun.awt.windows.ThemeReader;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 35326
 * 2021/3/22 9:52
 * 读写锁的例子
 */
 class ReadWriteLockDemo {
 	private static Lock lock = new ReentrantLock();
 	private static ReentrantReadWriteLock readWriteLock= new ReentrantReadWriteLock();
	private static Lock readLock= readWriteLock.readLock();
	private static Lock writeLock=readWriteLock.writeLock();
	private int value;

	public Object handleRead(Lock lock) throws InterruptedException{
		lock.lock();//模拟读操作
		try{

			Thread.sleep(1000);
			return value;
		}finally {
			lock.unlock();
		}
	}

	public void handleWrite(Lock lock,int index) throws InterruptedException{
		lock.lock();
		try{
			Thread.sleep(1000);
			value=index;
		}finally {
			lock.unlock();
		}
	}

	public static void main(String[] args) {
		final ReadWriteLockDemo demo = new ReadWriteLockDemo();
		Runnable readRunnable=()->{
				try{
					demo.handleRead(readLock);
//					demo.handleRead(lock);
				}catch (InterruptedException e){
					e.printStackTrace();
				}
		};

		Runnable writeRunnable =()->{
			try{
				demo.handleWrite(writeLock,new Random().nextInt());
//				demo.handleWrite(lock,new Random().nextInt());
			}catch (InterruptedException e){
				e.printStackTrace();
			}
		};

		long l = System.currentTimeMillis();
		for (int i = 0; i < 18; i++) {
			Thread thread = new Thread(readRunnable);
			thread.start();
			try {
				thread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i=18;i<20;i++){
			Thread thread = new Thread(writeRunnable);
			thread.start();
			try {
				thread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		long l1 = System.currentTimeMillis();
		System.out.println("耗时："+(l1-l));

	}
}
